package client.comm.commlib.base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import client.comm.commlib.toast.ToastFactory
import client.comm.commlib.toast.ToastFactory.Companion.isSnackBack
import com.bumptech.glide.RequestManager

abstract class BaseFragment<V : ViewDataBinding, VM : BaseAppViewModel>(contentLayoutId: Int = 0) :
    Fragment(contentLayoutId) {

    var conentId: Int = 0
    lateinit var binding: V
    lateinit var viewModel: VM
    lateinit var rootView: View

    init {
        conentId = contentLayoutId

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = initViewModel()
        if (requireActivity() is BaseActivity<*, *>) {
            (requireActivity() as BaseActivity<*, *>).parentOnresuse = {
                parentonResume()
            }
        }
        Log.i("BaseFragment", "onCreate")
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.i("BaseFragment", "onCreateView")

        setContentView(inflater, conentId, container)

        binding = DataBindingUtil.bind<V>(rootView.rootView) as V
        binding.lifecycleOwner = this

        initWidget()
        initData()
        parentonResume()
        return rootView
    }

    init {
        Log.i("BaseFragment", "init")
    }

    abstract fun getViewId(): Int
    fun setContentView(inflater: LayoutInflater, resId: Int, container: ViewGroup?) {
        rootView = inflater.inflate(getViewId(), container, false)
        rootView?.apply {
            rootView.parent?.apply {
                val parent = rootView.parent as ViewGroup
                parent.removeView(rootView)
            }
        }

    }

    abstract fun initViewModel(): VM

    inline fun <reified VM : ViewModel> createViewModel(): VM {
//        return ViewModelProvider(this).get(VM::class.java)
        return ViewModelProvider(requireActivity()).get(VM::class.java)
    }

    val mImgLoader: RequestManager by lazy {
        (requireActivity() as BaseActivity<*, *>).getImgLoader()
    }

    protected open fun initWidget() {}

    protected open fun initData() {}
    protected open fun parentonResume() {}

}